package me.shurufa.db;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;

import me.shurufa.utils.Global;

/**
 * 内容提供者 通过数据库提供【废弃】
 *
 * @FileName: me.shurufa.db.SrfProvider.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-25 10:21
 */
public class SrfProvider extends ContentProvider{

    private DatabaseHelper mHelper;

    public static final UriMatcher sMatcher;

    public static final int ID_DIALOGS = 2;

    public static final int ID_KVS = 3;

    public static final int ID_MESSAGES = 4;

    public long currUid = 0L;

    /**
     * 初始化
     */
    static{
        sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sMatcher.addURI(ShuRuFa.AUTHORITY, "dialogs", ID_DIALOGS);
        sMatcher.addURI(ShuRuFa.AUTHORITY, "kvs", ID_KVS);
        sMatcher.addURI(ShuRuFa.AUTHORITY, "messages", ID_MESSAGES);
    }


    @Override
    public boolean onCreate() {
        return true;
    }


    /**
     * 通过Uid创建数据库
     * @return
     */
    synchronized SQLiteDatabase getDatabase() {
        long uid = Global.getCurrentUid();
        if (mHelper == null || uid != currUid) {
            mHelper = new DatabaseHelper(getContext(), "shurufa" + uid + ".sqlite");
            currUid = uid;
        }
        return mHelper.getWritableDatabase();
    }


    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = getDatabase();
        String tables = null;
        String groupBy = null;
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = null;
        } else {
            orderBy = sortOrder;
        }
        Uri bindUri = null;
        switch (sMatcher.match(uri)){
            case ID_DIALOGS:
                tables = ShuRuFa.DialogColumns.TABLE_NAME;
                bindUri = uri;
                break;
            case ID_KVS:
                tables = ShuRuFa.KeyValueColumns.TABLE_NAME;
                break;
            case ID_MESSAGES:
                tables = ShuRuFa.MessageColumns.TABLE_NAME;
                bindUri = uri;
                break;
        }
        if (TextUtils.isEmpty(tables)) {
            return null;
        }
        qb.setTables(tables);
        Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy);
        if (bindUri != null)
            c.setNotificationUri(getContext().getContentResolver(), bindUri);
        return c;
    }

    @Override
    public String getType(Uri uri) {
        return null;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = getDatabase();
        String table = null;
        long rowId;
        int i = sMatcher.match(uri);
        Uri ret = null;
        switch (i){
            case ID_DIALOGS:
                table = ShuRuFa.DialogColumns.TABLE_NAME;
                long did = values.getAsLong("_id");
                if (db.update(table, values, "_id=" + did, null) == 0) {
                    db.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE);
                }
            return null;
            case ID_MESSAGES:
                table = ShuRuFa.MessageColumns.TABLE_NAME;
                break;
        }
        if (table != null) {
            db.beginTransaction();
            rowId = db.insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_REPLACE);
            db.setTransactionSuccessful();
            db.endTransaction();
            ret = ContentUris.withAppendedId(uri, rowId);
        }
        if (ret != null) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return ret;
    }

    @Override
    public int bulkInsert(Uri uri, ContentValues[] values) {
        SQLiteDatabase db = getDatabase();
        switch (sMatcher.match(uri)) {
            case ID_DIALOGS: {
                db.beginTransaction();
                for (ContentValues value : values) {
                    long did = value.getAsLong("_id");
                    if (db.update(ShuRuFa.DialogColumns.TABLE_NAME, value, "_id=" + did, null) == 0) {
                        db.insertWithOnConflict(ShuRuFa.DialogColumns.TABLE_NAME, null, value, SQLiteDatabase.CONFLICT_REPLACE);
                    }
                }
                db.setTransactionSuccessful();
                db.endTransaction();
                getContext().getContentResolver().notifyChange(uri, null);
            }
            return values.length;
            case ID_MESSAGES: {
                db.beginTransaction();
                for (ContentValues value : values) {
                    db.insertWithOnConflict(ShuRuFa.MessageColumns.TABLE_NAME, null, value, SQLiteDatabase.CONFLICT_REPLACE);
                }
                db.setTransactionSuccessful();
                db.endTransaction();
                getContext().getContentResolver().notifyChange(uri, null);
            }
            return values.length;
        }
        return super.bulkInsert(uri, values);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = getDatabase();
        int count = 0;
        Uri notifyUri = null;

        switch (sMatcher.match(uri)) {
            case ID_DIALOGS:
                count = db.delete(ShuRuFa.DialogColumns.TABLE_NAME,selection,selectionArgs);
                notifyUri = ShuRuFa.DialogColumns.CONTENT_URI;
                break;
        }
        if (notifyUri != null) {
            getContext().getContentResolver().notifyChange(notifyUri, null);
        }

        return count;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        int count = 0;
        SQLiteDatabase db = getDatabase();
        Uri notifyUri = null;
        switch (sMatcher.match(uri)){
            case ID_DIALOGS:
                count = db.update(ShuRuFa.DialogColumns.TABLE_NAME, values, selection,
                        selectionArgs);
                notifyUri = ShuRuFa.DialogColumns.CONTENT_URI;
                break;
            case ID_MESSAGES:
                count = db.update(ShuRuFa.MessageColumns.TABLE_NAME, values, selection,
                        selectionArgs);
                notifyUri = ShuRuFa.MessageColumns.CONTENT_URI;
                break;
            case ID_KVS:
                count = db.update(ShuRuFa.KeyValueColumns.TABLE_NAME, values, selection,
                        selectionArgs);
                break;
        }

        if (notifyUri != null) {
            getContext().getContentResolver().notifyChange(notifyUri, null);
        }
        return count;
    }
}
